//
//  QNCPDeviceManager.m
//  QNQNeviceModule_Example
//
//  Created by yolanda on 2025/6/9.
//  Copyright © 2025 刘观华. All rights reserved.
//

#import "QNCPDeviceManager.h"
#import "QNCPDeviceManager+Addition.h"
#import "QNCPDeviceEnum.h"
#import "QNCPDeviceUUID.h"

@interface QNCPDeviceManager ()<CBPeripheralDelegate,QNCentralManagerDelegate>

@end


@implementation QNCPDeviceManager
static QNCPDeviceManager *deviceManager = nil;

#pragma mark -
+ (QNCPDeviceManager *)sharedDeviceManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        deviceManager = [QNCPDeviceManager alloc];
        
    });
    return deviceManager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        deviceManager = [super allocWithZone:zone];
    });
    return deviceManager;
}

- (instancetype)initWithCentralManager:(QNCentralManager *)centralManager {
    if (self = [super init]) {
        if (self.delegates == nil) {
            self.delegates = [NSHashTable<id<QNCPDeviceDelegate>> hashTableWithOptions:NSPointerFunctionsWeakMemory];
        }
        self.centralManager = centralManager;
        self.centralManager.delegate = self;
    }
    return self;
}

- (void)setDelegate:(id<QNCPDeviceDelegate>)delegate {
    [self.delegates addObject:delegate];
}

- (QNCPDeviceState)scaleState {
    if (self.scaleDevice.peripheral.state == CBPeripheralStateConnecting) {
        return QNCPDeviceStateConnecting;
    }else if (self.scaleDevice.peripheral.state == CBPeripheralStateConnected) {
        return QNCPDeviceStateConnected;
    }else {
        return QNCPDeviceStateUnknow;
    }
}



#pragma mark - QNCentralManagerDelegate

/**
 蓝牙状态的更新
 
 @param state QNBlueToothState
 */
- (void)centralManagerBlueToothUpdateState:(QNBlueToothState)state {
    [self deviceLogMessage:[NSString stringWithFormat:@"系统蓝牙变化[%lu]", (unsigned long)state]];
    if (state != QNBlueToothStatePoweredOn) {
        self.scaleDevice = nil;
    }
}

/**
 返回当前连接的设备
 
 @return 外设
 */
- (nullable CBPeripheral *)centralManagerConnectionPeripheral {
    return self.scaleDevice.peripheral;
}


/**
 扫描操作的回调
 
 @param scanState QNCentralScanState
 */
- (void)centralScanStateUpdate:(QNCentralScanState)scanState {
    
}

/**
 连接状态的更新
 
 @param state QNPeripheralState
 @param peripheral CBPeripheral
 @param errCode 连接错误码
 @param error 错误信息
 */
- (void)centralManagerPeripheralUpdateState:(QNPeripheralState)state peripheral:(CBPeripheral *)peripheral errCode:(NSInteger)errCode error:(nullable NSError *)error {
    
}

/**
 发现设备
 
 @param peripheral CBPeripheral
 @param advertisementData NSDictionary<NSString *,id>
 @param rssi NSNumber
 */
- (void)centralDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData rssi:(NSNumber *)rssi {
    
    /// 过滤WSP服务器
    BOOL wspServiceVail = NO;
    if ([advertisementData.allKeys containsObject:@"kCBAdvDataServiceUUIDs"]) {
        for (CBUUID *item in advertisementData[@"kCBAdvDataServiceUUIDs"]) {
            if ([item.UUIDString.uppercaseString isEqualToString:QNWspServiceUUID] || [item.UUIDString.uppercaseString isEqualToString:QNWspSimplifyServiceUUID]) {
                NSData *manufacturerData = (NSData *)[advertisementData valueForKey:CBAdvertisementDataManufacturerDataKey];
                wspServiceVail = manufacturerData.length >= 17;
            }
        }
    }
    
    /// 过滤蓝牙名
    NSString *bleName = peripheral.name;
    if ([bleName isEqualToString:@"QN-KS"] || [bleName isEqualToString:@"QN-HS2"] || [bleName isEqualToString:@"QN-HS"] || [bleName hasPrefix:@"Hi-QNKS"] || [bleName hasPrefix:@"Hi-QNCM"]) {
        return;
    }
    
    if (wspServiceVail == YES) return;
    NSData *manufacturerData = (NSData *)[advertisementData valueForKey:CBAdvertisementDataManufacturerDataKey];
    if (manufacturerData.length < 16) return;
    const Byte *bytes = manufacturerData.bytes;
    NSString *prefixStr = [[NSString stringWithFormat:@"%02x%02x",bytes[0],bytes[1]] uppercaseString];
    if (![prefixStr isEqualToString:@"FFFF"]) return;
    
    // 带本地用户蓝牙秤
    if (bytes[13] != 0x66) return;
    
    //内部型号
    NSString *internalModel = [[NSString stringWithFormat:@"%02x%02x",bytes[2],bytes[3]] uppercaseString];
    //状态
    NSInteger status = bytes[5];
    //存储数据
    NSUInteger storageNum = (NSUInteger)bytes[6];
    //mac地址
    NSString *mac = nil;
    for (NSUInteger i = 12; i > 6; i --) {
        if (mac == nil) {
            mac = [NSString stringWithFormat:@"%02x",bytes[i]];
        }else{
            mac = [NSString stringWithFormat:@"%@:%02x",mac,bytes[i]];
        }
    }
    mac = [mac uppercaseString];
    int allowMaxUserNum = bytes[14];
    int registerUserNum = bytes[15];
    
    QNCPDevice *scaleDevice = [[QNCPDevice alloc] init];
    scaleDevice.mac = mac;
    scaleDevice.RSSI = rssi;
    scaleDevice.UUIDIdentifier = peripheral.identifier.UUIDString;
    scaleDevice.internalModel = internalModel;
    scaleDevice.allowMaxUserNum = allowMaxUserNum;
    scaleDevice.registerUserNum = registerUserNum;
    scaleDevice.peripheral = peripheral;
    if (bytes[13] == 0x61) {
        scaleDevice.deviceType = QNCPDeviceTypeCP10N;
    }
    
    
    scaleDevice.advertisementData = advertisementData;
    
    [self delegateSelectorOnMainThread:@selector(discoverCpDevice:) callBlock:^(id<QNCPDeviceDelegate>  _Nonnull delegate) {
        [delegate discoverCpDevice:scaleDevice];
    }];
    
}


@end
